package com.daigou.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daigou.constants.CommonConstants;
import com.daigou.model.Product;
import com.daigou.model.Shop;
import com.daigou.model.User;
import com.daigou.service.ProductService;
import com.daigou.service.ShopService;
import com.daigou.service.UserService;

@Controller
@RequestMapping(value = "/product")
public class ProductController {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class);
	@Autowired
	private ProductService productService;
	@Autowired
	private ShopService shopService;
	@Autowired
    private UserService userService;
	
	@RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public String toProductPage(HttpServletRequest request,Model model,@PathVariable("id")Long id){
		LOGGER.info("进入商品详情{}",id);
		Product product = productService.selectByPrimaryKey(id);
		Shop shop = shopService.selectByPrimaryKey(product.getShopId());
		User user = userService.selectByPrimaryKey(shop.getSalerId());
		model.addAttribute("user", user);
		model.addAttribute("shop", shop);
		model.addAttribute("product", product);
		List<Product> productList = productService.selectByShopId(shop.getId(),1, null);
		if(productList != null && productList.size() > 6){
			model.addAttribute("product6List", productList.subList(0, 5));
		}else{
			model.addAttribute("product6List", productList);
		}
		model.addAttribute("productList", productList);
		Integer onSaleCount = productService.selectOnSaleCountByShopId(shop.getId());
		model.addAttribute("onSaleCount", onSaleCount);
		Cookie[] cookies = request.getCookies();
		String loginName = "0";
		if (null == cookies) {
			LOGGER.info("没有cookie==============");
		} else {
			//遍历cookie如果找到登录状态则返回true执行原来controller的方法
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CommonConstants.LOGIN_NAME)) {
					loginName = cookie.getValue();
					LOGGER.info("cookie(loginName)=============="+loginName);
					continue;
				}
			}
		}
		model.addAttribute("loginName", loginName);
        return "/shop/app/product";
    }
}
